/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.icanci.loopstack.damc.core.service;

import org.springframework.context.ApplicationContext;

import cn.icanci.loopstack.damc.api.groovy.GroovyClassLoaderHolder;
import cn.icanci.loopstack.damc.core.extension.DisposableRunnerHandler;

/**
 * 一次性执行服务
 * 
 * @author icanci(1205068)
 * @version Id: DisposableRunnerService, v 0.1 2025/5/26 20:35 icanci Exp $
 */
public class DisposableRunnerService {
    /**
     * Spring 上下文
     */
    private static ApplicationContext context;

    public static void setContext(ApplicationContext context) {
        DisposableRunnerService.context = context;
    }

    /**
     * 一次性执行invoke
     *
     * @param appCode appCode
     * @param script script
     */
    public static void invoke(String appCode, String script) {
        try {
            // 记录日志
            log(appCode, script);
            // 此处是本地函数调用（只能是本地调用）
            Class<?> compile = GroovyClassLoaderHolder.compile(script);
            Object instance = compile.newInstance();
            if (instance instanceof DisposableRunnerHandler) {
                DisposableRunnerHandler handler = (DisposableRunnerHandler) instance;
                // 全限定类名重复的处理。此处无需处理，
                // 经过 GroovyClassLoaderHolder.compile 的class对象是不重复的，即使代码是完全一样的

                // 处理 Spring 使用@Resource 注入
                injectionSpringBeanProcessor(handler);

                handler.invoke();
            }
            throw new IllegalArgumentException("class must implements MockRunnerHandler");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 记录日志
     *
     * @param appCode appCode
     * @param script script
     */
    private static void log(String appCode, String script) {
        String format = "[DisposableRunnerService][log] appCode:[%s],the script:[%s]";
        System.out.printf((format) + "%n", appCode, script);
    }

    /**
     * 后置注入Bean
     *
     * @param handler handler
     */
    public static void injectionSpringBeanProcessor(DisposableRunnerHandler handler) {
        context.getAutowireCapableBeanFactory().autowireBean(handler);
    }
}